package com.haotunet.app.goldtreasure.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.db.DBOpenHelper;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.ExchangePageInfo;
import com.haotunet.app.goldtreasure.model.OrderInfo;
import com.haotunet.app.goldtreasure.model.StoreInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.OrderPopupView;

public class StoreExchangeReserveAct extends BaseActivity implements OnClickListener {
    private TextView mTitleTxt;
    private ImageView ivBack;
    private RelativeLayout rlLocate;
    private View rootView;
    private ImageView mStoreImage;
    private TextView mShopName, mShopAddress;
    private TextView mContactPerson, mContactNum;
    private EditText mExchangeGramsTxt;
    private TextView mExtractGold;
    private TextView mExchangeTips;
    private Button btnResever;
    private ImageView btnCall;
    private DBOpenHelper helper;
    private OrderInfo orderInfo;
    private String availableGold;
    private final int SUBMIT_EXCHANGE_RESEVER_INFO_SUCCESS = 1;
    private Handler handle = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {

                case SUBMIT_EXCHANGE_RESEVER_INFO_SUCCESS:
                    orderInfo = (OrderInfo) msg.obj;
                    if (shareStore.getInt(Strs.IS_HAD_BANK_CARD, 0) == 0) {
                        ActivityUtils.gotoNewUserBuy(StoreExchangeReserveAct.this, "4", orderInfo);
                    } else {
                        showOrderDetailView();
                    }
                    break;
                default:
                    break;
            }
        }

    };

    private String shopId;
    private StoreInfo info;
    private ShareStore shareStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_exchange_reserve);
        tintManager.setStatusBarAlpha(0f);
        helper = new DBOpenHelper(StoreExchangeReserveAct.this);
        shareStore = new ShareStore(this);
        initView();
        getExchangePageInfo();
    }

    private void initView() {
        info = (StoreInfo) getIntent().getSerializableExtra("storeDetailInfo");
        shopId = getIntent().getStringExtra("shopId");
        rootView = findViewById(R.id.root);
        mTitleTxt = (TextView) findViewById(R.id.title_txt);
        mTitleTxt.setText("换购黄金");
        ivBack = (ImageView) findViewById(R.id.iv_left_arrow);
        rlLocate = (RelativeLayout) findViewById(R.id.locate_layout);
        mStoreImage = (ImageView) findViewById(R.id.shop_image);
        if (!TextUtils.isEmpty(info.getImage())) {
            Glide.with(StoreExchangeReserveAct.this).load(info.getImage().trim()).placeholder(R.drawable.placeholder_shop_big).error(R.drawable.placeholder_shop_big).into(mStoreImage);
        }
        mShopName = (TextView) findViewById(R.id.shop_name);
        mShopName.setText(info.getShopName());
        mShopAddress = (TextView) findViewById(R.id.shop_address);
        mShopAddress.setText(info.getAddress());
        btnCall = (ImageView) findViewById(R.id.iv_call);
        mContactNum = (TextView) findViewById(R.id.txt_contact_phone);
        mContactNum.setText(helper.getMobile());
        mContactPerson = (TextView) findViewById(R.id.txt_contact_person);
        mContactPerson.setText(helper.getRealName());
        mExtractGold = (TextView) findViewById(R.id.can_extract_gold);
        mExchangeTips = (TextView) findViewById(R.id.exchange_tips);
        mExchangeGramsTxt = (EditText) findViewById(R.id.et_exchange_grams);
        btnResever = (Button) findViewById(R.id.btn_submit_reserve);
        mExchangeGramsTxt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String inputString = s.toString();
                if (inputString.contains(".")) {
                    if (inputString.length() - 1 - inputString.toString().indexOf(".") > 3) {
                        inputString = (String) inputString.subSequence(0, inputString.indexOf(".") + 4);
                        mExchangeGramsTxt.setText(inputString);
                        mExchangeGramsTxt.setSelection(inputString.length());
                    }
                }
                if (inputString.trim().substring(0).equals(".")) {
                    inputString = "0";
                    mExchangeGramsTxt.setText(inputString);
                    mExchangeGramsTxt.setSelection(1);
                }
                if (inputString.startsWith("0") && inputString.trim().length() > 1) {
                    if (!inputString.substring(1, 2).equals(".")) {
                        mExchangeGramsTxt.setText(inputString.subSequence(1, 2));
                        mExchangeGramsTxt.setSelection(1);
                        return;
                    }
                }
            }
        });
        ivBack.setOnClickListener(this);
        rlLocate.setOnClickListener(this);
        btnCall.setOnClickListener(this);
        btnResever.setOnClickListener(this);
    }

    private void getExchangePageInfo() {
        ActionUtil actionUtil = new ActionUtil(StoreExchangeReserveAct.this);
        actionUtil.getExchangePageInfo();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                ExchangePageInfo pageInfo = (ExchangePageInfo) model;
                if (pageInfo == null) {
                    UIHelper.showToast(StoreExchangeReserveAct.this, getString(R.string.rank_fail));
                    return;
                }
                if (pageInfo.getErrorMsg() != null) {
                    if (pageInfo.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(StoreExchangeReserveAct.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(StoreExchangeReserveAct.this, pageInfo.getErrorMsg());
                    }
                } else {
                    mExchangeTips.setText(pageInfo.getTips());
                    availableGold = pageInfo.getAvailableGold();
                    mExtractGold.setText("可用流动金：" + availableGold);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left_arrow:
                finish();
                break;
            case R.id.locate_layout:
                if (info != null) {
                    ActivityUtils.gotoShopPosition(StoreExchangeReserveAct.this, info.getAddress(), info.getPoint().getX(),
                            info.getPoint().getY(), info.getShopName());
                }
                break;
            case R.id.iv_call:
                if (info != null) {
                    UIHelper.showCallRemindDialog(StoreExchangeReserveAct.this, info.getShopPhone());
                }
                break;
            case R.id.btn_submit_reserve:
                String exchangeGrams = mExchangeGramsTxt.getText().toString().trim();
                if (TextUtils.isEmpty(exchangeGrams)) {
                    UIHelper.showToast(StoreExchangeReserveAct.this, "请输入换购克数!");
                    return;
                }
                double inputGrams = Double.parseDouble(exchangeGrams);
                if (inputGrams == 0) {
                    UIHelper.showToast(StoreExchangeReserveAct.this, "换购克数不能为0!");
                    return;
                }
                if (inputGrams > Double.parseDouble(availableGold)) {
                    UIHelper.showToast(StoreExchangeReserveAct.this, "可用黄金克数不足!");
                    return;
                }
                submitExchangeReseverInfo(exchangeGrams);
                break;
            default:
                break;
        }
    }

    private void submitExchangeReseverInfo(String exchangeGrams) {

        ActionUtil actionUtil = new ActionUtil(StoreExchangeReserveAct.this);
        actionUtil.submitExchangeReseverInfo(exchangeGrams, shopId);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                OrderInfo orderInfo = (OrderInfo) model;
                if (orderInfo == null) {
                    UIHelper.showToast(StoreExchangeReserveAct.this, getString(R.string.rank_fail));
                    return;
                }
                if (orderInfo.getErrorMsg() != null) {
                    if (orderInfo.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(StoreExchangeReserveAct.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(StoreExchangeReserveAct.this, orderInfo.getErrorMsg());
                    }
                } else {
                    Message msg = new Message();
                    msg.what = SUBMIT_EXCHANGE_RESEVER_INFO_SUCCESS;
                    msg.obj = orderInfo;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    private void showOrderDetailView() {
        OrderPopupView orderPopupView = new OrderPopupView(StoreExchangeReserveAct.this, orderInfo.getPayment(), "4",
                orderInfo);
        orderPopupView.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
        ActivityUtils.backgroundAlpha(StoreExchangeReserveAct.this, 0.5f);
        orderPopupView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ActivityUtils.backgroundAlpha(StoreExchangeReserveAct.this, 1f);
            }
        });
    }

}
